package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1.准备request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            //2.1query
            //构建BooleanQuery
            buildBasicQuery(params, request);


            //2.2分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page-1) * size).size(size);

            //2.3地理排序

            String location = params.getLocation();
            if (location!=null && !"".equals(location)){
                request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                .order(SortOrder.ASC)
                .unit(DistanceUnit.KILOMETERS)
                );
            }

            // 3.发送请求，得到响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.1结果解析获取总条数
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        // 1.准备request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        //2.2query
        buildBasicQuery(params, request);
        // 2.2设置size
        request.source().size(0);
        buildAggregation(request);
        // 3.发送请求，得到响应
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4解析结果
        Map<String,List<String>> result=new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        List<String> brandList = getAggByName(aggregations,"brandAgg");
        //4.4放入map
        result.put("品牌",brandList);

        List<String> cityList = getAggByName(aggregations,"cityAgg");
        //4.4放入map
        result.put("城市",cityList);

        List<String> starList = getAggByName(aggregations,"starAgg");
        //4.4放入map
        result.put("星级",starList);
        return result;
    }

    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            // 1.准备request
            SearchRequest request = new SearchRequest("hotel");
            // 2.DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //3发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            List<String> list=new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
               list.add(s);
            }

            return list;
        } catch (IOException e) {
           throw new RuntimeException();
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request      // DELETE /hotel/_doc/{id}
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            //0根据id查酒店信息
            Hotel hotel = getById(id);

            // 2.转换为HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 3.转JSON
            String json = JSON.toJSONString(hotelDoc);
            // 1.准备Request
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            // 2.准备请求参数DSL，其实就是文档的JSON字符串
            request.source(json, XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private void buildAggregation(SearchRequest request) {
        //2.2进行聚合
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }

    private List<String> getAggByName(Aggregations aggregations,String aggName) {
        //4.1根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);

        //4.2获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //4.3遍历
        List<String> brandList=new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
           brandList.add(key);
        }
        return brandList;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        if (key==null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //城市条件过滤
        String city = params.getCity();
        if (city!=null  && !"".equals(city)){
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }

        //品牌条件过滤
        String brand = params.getBrand();
        if (brand!=null  && !"".equals(brand)){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        //品牌条件过滤
        String starName = params.getStarName();
        if (starName!=null  && !"".equals(starName)){
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }

        //价格范围过滤
        if (params.getMinPrice()!=null  && params.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders
                            .rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice())
                    );
        }
        if (params.getMinPrice()==null){
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price").lte(params.getMaxPrice())
            );
        }
        if (params.getMaxPrice()==null){
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price").gte(params.getMinPrice())
            );
        }

        //2算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        //原始查询相关性算分
                        boolQuery,
                        //functionscore的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                //function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD",true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });




        request.source().query(boolQuery);
    }

    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("总条数：" + total);
        // 4.2.获取文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        ArrayList<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 4.4.获取source
            String json = hit.getSourceAsString();
            // 4.5.反序列化，非高亮的

            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        return new PageResult(total,hotels);
    }
}
